package com.guochenglang.www.util;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;

/**
 * 生成图片验证码
 *
 * @author GuoChenglang
 */
public class GetBufferedImage {
    /**
     * 生成图片验证码
     *
     * @param code 验证码
     */
    public static void drawCode(String code, HttpServletResponse response) throws IOException {
        Random random = new Random();
        //生成画板，指定画板大小
        BufferedImage bufferedImage = new BufferedImage(80, 30, BufferedImage.TYPE_INT_RGB);
        //生成画笔
        Graphics2D graphics = bufferedImage.createGraphics();
        int red = random.nextInt(255);
        int green = random.nextInt(255);
        int blue = random.nextInt(255);
        Color inColor = new Color(red, green, blue);
        int red2 = random.nextInt(255);
        int green2 = random.nextInt(255);
        int blue2 = random.nextInt(255);
        Color outColor = new Color(red2, green2, blue2);
        BufferedImage outImage = new BufferedImage(80, 30, BufferedImage.TYPE_INT_RGB);
        //获得颜色
        graphics.setColor(inColor);
        graphics.fillRect(0, 0, 80, 30);
        //获得颜色
        graphics.setColor(outColor);
        graphics.setFont(new Font("黑体", Font.BOLD, 30));
        //根据验证码绘图
        graphics.drawString(code, 10, 30);
        //存到流中
        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(bufferedImage, "jpeg", outputStream);
    }
}
